package com.bawei.module_mine.ui

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.utils.UserUtils
import com.bawei.lib_storage.room.FavoriteManager
import com.bawei.module_mine.adapter.FavoriteAdapter
import com.bawei.module_mine.databinding.ActivityStoreBinding
import kotlinx.coroutines.launch

@Route(path = "/module_mine/StoreActivity")
class StoreActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityStoreBinding
    private lateinit var favoriteAdapter: FavoriteAdapter
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityStoreBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initView()
        initData()
    }
    
    private fun initView() {
        // 初始化RecyclerView
        favoriteAdapter = FavoriteAdapter()
        binding.rvFavorites.adapter = favoriteAdapter
        binding.rvFavorites.layoutManager = LinearLayoutManager(this)
        
        // 设置点击事件
        favoriteAdapter.onItemClickListener = { favoriteEntity ->
            // 跳转到视频详情页面
            navigateToVideoDetail(favoriteEntity)
        }
        
        // 设置取消收藏事件
        favoriteAdapter.onUnfavoriteClickListener = { favoriteEntity ->
            // 取消收藏
            unfavoriteVideo(favoriteEntity)
        }
        
        // 设置返回按钮
        binding.ivBack.setOnClickListener {
            finish()
        }
        
        // 设置清空收藏按钮
        binding.tvClearAll.setOnClickListener {
            clearAllFavorites()
        }
    }
    
    private fun initData() {
        loadFavoriteData()
    }
    
    /**
     * 加载收藏数据
     */
    private fun loadFavoriteData() {
        lifecycleScope.launch {
            try {
                // 获取当前用户ID
                val userId = UserUtils.getCurrentUserId()
                
                Log.d("StoreActivity", "开始加载收藏数据，用户ID: '$userId'")
                
                if (userId.isNotEmpty()) {
                    // 用户已登录，获取该用户的收藏
                    val favoriteList = FavoriteManager.getFavoriteListByUserId(userId)
                    if (favoriteList.isNotEmpty()) {
                        favoriteAdapter.setData(favoriteList)
                        binding.tvEmpty.visibility = android.view.View.GONE
                        binding.rvFavorites.visibility = android.view.View.VISIBLE
                        Log.d("StoreActivity", "加载用户收藏成功，用户ID: $userId, 数量: ${favoriteList.size}")
                    } else {
                        favoriteAdapter.setData(emptyList())
                        binding.tvEmpty.visibility = android.view.View.VISIBLE
                        binding.rvFavorites.visibility = android.view.View.GONE
                        Log.d("StoreActivity", "用户暂无收藏，用户ID: $userId")
                    }
                } else {
                    // 用户未登录，使用默认用户ID
                    val defaultUserId = UserUtils.getDefaultUserId()
                    Log.d("StoreActivity", "用户未登录，使用默认用户ID: $defaultUserId")
                    
                    val favoriteList = FavoriteManager.getFavoriteListByUserId(defaultUserId)
                    if (favoriteList.isNotEmpty()) {
                        favoriteAdapter.setData(favoriteList)
                        binding.tvEmpty.visibility = android.view.View.GONE
                        binding.rvFavorites.visibility = android.view.View.VISIBLE
                        Log.d("StoreActivity", "加载默认用户收藏成功，数量: ${favoriteList.size}")
                    } else {
                        favoriteAdapter.setData(emptyList())
                        binding.tvEmpty.visibility = android.view.View.VISIBLE
                        binding.rvFavorites.visibility = android.view.View.GONE
                        Log.d("StoreActivity", "默认用户暂无收藏")
                    }
                }
            } catch (e: Exception) {
                Log.e("StoreActivity", "加载收藏数据失败: ${e.message}", e)
                favoriteAdapter.setData(emptyList())
                binding.tvEmpty.visibility = android.view.View.VISIBLE
                binding.rvFavorites.visibility = android.view.View.GONE
                Toast.makeText(this@StoreActivity, "加载收藏失败", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    /**
     * 取消收藏
     */
    private fun unfavoriteVideo(favoriteEntity: com.bawei.lib_storage.room.entity.FavoriteEntity) {
        lifecycleScope.launch {
            try {
                val userId = UserUtils.getCurrentUserId().ifEmpty { UserUtils.getDefaultUserId() }
                val success = FavoriteManager.removeFavorite(userId, favoriteEntity.videoId)
                
                if (success) {
                    Toast.makeText(this@StoreActivity, "已取消收藏", Toast.LENGTH_SHORT).show()
                    // 重新加载数据
                    loadFavoriteData()
                } else {
                    Toast.makeText(this@StoreActivity, "取消收藏失败", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Log.e("StoreActivity", "取消收藏失败: ${e.message}", e)
                Toast.makeText(this@StoreActivity, "取消收藏失败", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    /**
     * 清空所有收藏
     */
    private fun clearAllFavorites() {
        lifecycleScope.launch {
            try {
                val userId = UserUtils.getCurrentUserId().ifEmpty { UserUtils.getDefaultUserId() }
                FavoriteManager.clearAllFavoritesByUserId(userId)
                
                Toast.makeText(this@StoreActivity, "已清空所有收藏", Toast.LENGTH_SHORT).show()
                // 重新加载数据
                loadFavoriteData()
            } catch (e: Exception) {
                Log.e("StoreActivity", "清空收藏失败: ${e.message}", e)
                Toast.makeText(this@StoreActivity, "清空收藏失败", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    /**
     * 跳转到视频详情页面
     */
    private fun navigateToVideoDetail(favoriteEntity: com.bawei.lib_storage.room.entity.FavoriteEntity) {
        try {
            // 组装VideoEntity对象
            val videoEntity = com.bawei.module_detail.model.entity.VideoEntity(
                avatar_url = favoriteEntity.authorImg,
                channelid = favoriteEntity.channelId,
                commentnum = 0,
                ctime = "",
                description = favoriteEntity.content,
                group_id = "",
                id = 0,
                image_url = favoriteEntity.primaryImg,
                item_id = favoriteEntity.videoId,
                labelIds = "",
                name = favoriteEntity.authorName,
                playnum = 0,
                preview_url = favoriteEntity.primaryImg,
                publish_time = "",
                title = favoriteEntity.title,
                userid = favoriteEntity.userId,
                verifycode = "",
                videomainimag = favoriteEntity.primaryImg,
                videopath = favoriteEntity.videoPath
            )
            
            // 使用ARouter跳转到详情页
            com.alibaba.android.arouter.launcher.ARouter.getInstance()
                .build("/detail/DetailActivity")
                .withString("detail", com.google.gson.Gson().toJson(videoEntity))
                .navigation()
                
        } catch (e: Exception) {
            Log.e("StoreActivity", "跳转详情页失败: ${e.message}", e)
            Toast.makeText(this, "跳转失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onResume() {
        super.onResume()
        // 每次页面恢复时刷新收藏数据
        loadFavoriteData()
    }
}